<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket 示例</title>
  </head>
  <body>
    <button>发消息给服务器</button>
    <script>
      // 实例化 socket
      const ws = new WebSocket('ws://124.222.224.186:8800')
      // 监听连接的建立
      ws.onopen = function (ev) {
        console.log('建立连接...')
        // ws.send('Hello WebSockets!')
      }
      // 监听连接的断开
      ws.onclose = function (ev) {
        console.log('断开连接...')
      }
      // 监听 socket 服务器消息
      ws.onmessage = function (ev) {
        console.log('收到消息: ' + ev.data)
      }
      document.querySelector('button').addEventListener('click', function () {
        ws.send(`你好呀，我今年${Math.floor(Math.random() * 100)}`)
      })
    </script>
  </body>
</html>
